package com.example.demo.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.demo.enums.CommonCodeEnum;
import com.example.demo.entity.BmDatasourceManagement;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Component
public class DataSourceManager {

	@Value("${spring.datasource.druid.url}")
	private String jdbcUrl;

	@Value("${spring.datasource.druid.username}")
	private String userName;

	@Value("${spring.datasource.druid.password}")
	private String password;

	@Value("${spring.datasource.druid.driver-class-name:com.mysql.cj.jdbc.Driver}")
	private String driverClassName;

	Map<String, DruidDataSource> dataSourceMap;

	public DataSourceManager() {
		this.dataSourceMap = new HashMap<>();
	}

	/**
	 * 获取数据库连接池，参数为null时，返回默认当前服务链接的数据库
	 * @param datasource
	 * @return
	 */
	public DruidDataSource getDataSourcePool(BmDatasourceManagement datasource){
		if (Objects.isNull(datasource)){
			log.info("缺少数据源信息,返回默认数据源");
			DruidDataSource defaultDataSource = dataSourceMap.get(CommonCodeEnum.DEFAULT_DATA_SOURCE.getCode());
			if (defaultDataSource == null || defaultDataSource.isClosed()) {
				log.info("初始化当前服务数据库连接池");
				// 初始化源
				datasource = new BmDatasourceManagement();
				datasource.setSrcUrl(jdbcUrl);
				datasource.setEncUser(userName);
				datasource.setEncPass(password);
//				datasource.setEncPass(driverClassName);
				defaultDataSource = initDatasource(datasource);
				dataSourceMap.put(CommonCodeEnum.DEFAULT_DATA_SOURCE.getCode(), defaultDataSource);
			}
			return defaultDataSource;
		}
		String key = datasource.getDatasourceId();
		DruidDataSource druidDataSource = dataSourceMap.get(key);
		if (druidDataSource == null || druidDataSource.isClosed()) {
			// 初始化源
			log.info("初始化当前数据源连接池，连接信息：{}",datasource);
			try {
				druidDataSource = initDatasource(datasource);
				dataSourceMap.put(key, druidDataSource);
			} catch (Exception e) {
				log.error("初始化数据源连接池异常");
				e.printStackTrace();
			}

		}
		return druidDataSource;

	}

	public void closeConnection(Connection connection, PreparedStatement statement) {
		try {
			if (statement != null) {
				statement.close();
			}
			if (connection != null) {
				connection.close();
				log.info("====================connection closed :" + connection.isClosed());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}


	private DruidDataSource initDatasource(BmDatasourceManagement jobDatasource) {
		DruidDataSource druidDataSource = new DruidDataSource();
		druidDataSource.setDriverClassName(driverClassName);
		druidDataSource.setUrl(jobDatasource.getSrcUrl());
		druidDataSource.setUsername(jobDatasource.getEncUser());
		druidDataSource.setPassword(jobDatasource.getEncPass());
		druidDataSource.setInitialSize(5);
		druidDataSource.setMinIdle(5);
		druidDataSource.setMaxActive(40);
		druidDataSource.setTestWhileIdle(true);
		druidDataSource.setTimeBetweenEvictionRunsMillis(180000);
		druidDataSource.setValidationQuery("select 1");
		druidDataSource.setTestOnBorrow(true);
		druidDataSource.setTestOnReturn(true);
		return druidDataSource;
	}
}
